﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Reflection;
using System.Text;

namespace Dapper_Core.Common
{
    public class DataTableUtility
    {
        #region  将集合类转换成DataTable
        /// <summary>    
        /// 将集合类转换成DataTable    
        /// </summary>    
        /// <param name="list">集合</param>    
        /// <returns></returns>    
        public static DataTable ToDataTableTow(IList list)
        {
            DataTable result = new DataTable();
            if (list.Count > 0)
            {
                PropertyInfo[] propertys = list[0].GetType().GetProperties();

                foreach (PropertyInfo pi in propertys)
                {
                    result.Columns.Add(pi.Name, pi.PropertyType);
                }
                for (int i = 0; i < list.Count; i++)
                {
                    ArrayList tempList = new ArrayList();
                    foreach (PropertyInfo pi in propertys)
                    {
                        object obj = pi.GetValue(list[i], null);
                        tempList.Add(obj);
                    }
                    object[] array = tempList.ToArray();
                    result.LoadDataRow(array, true);
                }
            }
            return result;
        }
        #endregion

        #region 将泛型集合类转换成DataTable 
        /// <summary>    
        /// 将泛型集合类转换成DataTable    
        /// </summary>    
        /// <typeparam name="T">集合项类型</typeparam>    
        /// <param name="list">集合</param>    
        /// <returns>数据集(表)</returns>    
        public static DataTable ToDataTable<T>(IList<T> list)
        {
            return ToDataTable<T>(list, null);
        }
        #endregion

        #region 将泛型集合类转换成DataTable
        /// <summary>    
        /// 将泛型集合类转换成DataTable    
        /// </summary>    
        /// <typeparam name="T">集合项类型</typeparam>    
        /// <param name="list">集合</param>    
        /// <param name="propertyName">需要返回的列的列名</param>    
        /// <returns>数据集(表)</returns>    
        public static DataTable ToDataTable<T>(IList<T> list, params string[] propertyName)
        {
            try
            {
                List<string> propertyNameList = new List<string>();
                if (propertyName != null)
                    propertyNameList.AddRange(propertyName);
                DataTable result = new DataTable();
                if (list.Count > 0)
                {
                    PropertyInfo[] propertys = list[0].GetType().GetProperties();
                    foreach (PropertyInfo pi in propertys)
                    {
                        if (propertyNameList.Count == 0)
                        {
                            result.Columns.Add(pi.Name);
                            //result.Columns.Add(pi.Name, pi.PropertyType);
                        }
                        else
                        {
                            if (propertyNameList.Contains(pi.Name))
                                result.Columns.Add(pi.Name, pi.PropertyType);
                            //result.Columns.Add(pi.Name);
                        }
                    }

                    for (int i = 0; i < list.Count; i++)
                    {
                        ArrayList tempList = new ArrayList();
                        foreach (PropertyInfo pi in propertys)
                        {
                            if (propertyNameList.Count == 0)
                            {
                                object obj = pi.GetValue(list[i], null);
                                tempList.Add(obj);
                            }
                            else
                            {
                                if (propertyNameList.Contains(pi.Name))
                                {
                                    object obj = pi.GetValue(list[i], null);
                                    tempList.Add(obj);
                                }
                            }
                        }
                        object[] array = tempList.ToArray();
                        result.LoadDataRow(array, true);
                    }
                }
                return result;
            }
            catch (Exception)
            { 
                throw;
            }
        }
        #endregion

        #region 将datatable写入TextWriter中
        /// <summary>
        /// 将datatable写入TextWriter中
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="w"></param>
        public static void DataTableToWriter(DataTable dt, StringWriter w)
        {
            try
            {
                //读取表头
                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    w.Write(dt.Columns[i]);
                    w.Write('\t');
                }
                w.Write("\r\n");
                object[] values = new object[dt.Columns.Count];
                //读取数据行
                foreach (DataRow dr in dt.Rows)
                {
                    values = dr.ItemArray;
                    for (int i = 0; i < dt.Columns.Count; i++)
                    {
                        w.Write(values[i]);
                        w.Write('\t');
                    }
                    w.Write("\r\n");
                }
                w.Flush();
                w.Close();
            }
            catch
            {
                w.Close();
            }
        }
        #endregion

        #region 获取DataTable中指定列的数据
        /// <summary>
        /// 获取DataTable中指定列的数据
        /// </summary>
        /// <param name="dt">数据源</param>
        /// <param name="tableName">新的DataTable的名称</param>
        /// <param name="strColumns">指定的列名集合</param>
        /// <returns>返回新的DataTable</returns>
        public static DataTable GetTableColumn(DataTable dt, string tableName, params string[] strColumns)
        {
            DataTable dtn = new DataTable();
            if (dt == null)
            {
                throw new ArgumentNullException("参数dt不能为null");
            }
            try
            {
                dtn = new DataView(dt).ToTable(tableName, false, strColumns);
                //dtn = dt.DefaultView.ToTable(tableName, true, strColumns);
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }
            return dtn;
        }
        #endregion
    }
}
